import React, { Component, PropTypes } from 'react';
import { Form, Icon, Input, Button, Radio, Checkbox, message } from 'antd';
import Md5 from 'js-md5';
import { connect } from 'dva'
import Style from './login.less';
import Service from '../service';

const FormItem = Form.Item;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 17 },
};
const VerifLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 6 },
};
const imgLayout = { position: 'absolute', width: '90px', marginLeft: '20px', cursor: 'pointer' };
class ImgElement extends Component {
  constructor(props) {
    super(props);
    this.state = {
      keyNum: 1
    }
  }
  componentWillMount() {
    this.setState({
      keyNum: Math.random()
    });
  }
  handleClick = () => {
    this.setState({
      keyNum: Math.random()
    });
  }
  render() {
    const addr = `${Service.baseUrl}/earlywarn/authCode/authCode?random=${this.state.keyNum}`;
    // const addr = `http://${window.location.host}/earlywarn/authCode/authCode?random=${this.state.keyNum}`;
    return (
      <img src={addr} style={imgLayout} key={this.state.keyNum} onClick={this.handleClick} />

    );
  }
}
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      userMsg: {},
      keyNum: 1,
      isClear: false,
      str: 'password',
      text: '密码',
      userType: '1'
    }
  }
  /* 控制提示 */
  messageConfig() {
    message.config({
      top: 100, // 消息距离顶部的位置
      duration: 2, // 默认自动关闭延时，单位秒
      maxCount: 1, // 最大显示数, 超过限制时，最早的消息会被自动关闭
    });
  }
  handleSubmit = (e) => {
    var self = this;
    e.preventDefault();
    self.props.form.validateFields((err, values) => {
      if (!err) {
        const params = {
          username: values.name,
          password: values.password,
          // type:self.state.userType,
          zhuce: (data) => {
            if (data) {
              console.log(data)
              localStorage.setItem('userDetail', JSON.stringify(data));
              localStorage.setItem('token', data.token);
              self.messageConfig();
              message.success('登录成功!', 1.5, function () {
                self.context.router.push(`/1/app/mindex`);
              })

            }

          }
        }
        self.props.queryUser({ ...params });
        //this.props.saveUser({ id: '131341313431', user: '蛮王' })
      }
    });
  }
  // 密码明文暗纹
  pwdtap = (e) => {
    if (this.state.str == 'text') {
      this.setState({ str: 'password', text: '密码' })

    } else {
      this.setState({ str: 'text', text: '明文' })

    }
  }
  // 监听用户名输入
  listenUser = (e) => {
    let v = this.props.form.getFieldValue('name');
    if (v) {
      this.setState({
        isClear: true,
      })
      this.props.form.setFields({ "name": v });
    }
  }
  //  清空用户名
  clearUser = (e) => {
    this.props.form.setFields({ "name": "" });
    this.setState({
      isClear: false,
    })
  }
  repasswordFun = (e) => {
    this.context.router.push(`/repassword`)
  }
  registerFun = (e) => {
    this.context.router.push(`/register`)
  }
  // 单选按钮
  radioFun = (e) => {
    let self = this;
    let v = e.target.value;
    this.setState({
      userType: e.target.value
    })
    // console.log(v)
    if (v == 'k') {
      self.context.router.push(`/klogin`)
    }
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <div className={Style.loginBoxs}>
        <div className={Style.navTitle}>
          登录
        </div>
        <div className={Style.authBoxs}>
          <div className={Style.content}>
            <div className={Style.inputBox}>
              <Form onSubmit={this.handleSubmit} className="login-form">
                <FormItem label='账号' {...formItemLayout}>
                  {getFieldDecorator('name', {
                    rules: [{ required: true, message: '请输入账号!' }]
                  })(
                    <Input onBlur={this.listenUser} placeholder="账号" autoComplete="username" />
                    )}
                  {
                    this.state.isClear &&
                    <div className={Style.loginIcon} onClick={this.clearUser}></div>
                  }
                </FormItem>

                <FormItem label='密码' {...formItemLayout}>
                  {getFieldDecorator('password', {
                    rules: [{ required: true, message: '请输入密码!' }]
                  })(
                    <Input placeholder="密码" type={this.state.str} autoComplete="current-password" />
                    )}
                  {this.state.str == 'text' &&
                    <div className={Style.loginIcon + ' ' + Style.loginPwdClose} onClick={this.pwdtap}></div>
                  }
                  {this.state.str != 'text' &&
                    <div className={Style.loginIcon + ' ' + Style.loginPwdShow} onClick={this.pwdtap}></div>
                  }
                </FormItem>
                <div className={Style.mb15 + ' ' + "formtype"}>
                  <RadioGroup onChange={this.radioFun} defaultValue="m" className={Style.radioWrapItem}>
                    <RadioButton value="m">管理员</RadioButton>
                    <RadioButton value="k">快递员</RadioButton>
                  </RadioGroup>
                </div>

                {/* <div className={Style.formRight} onClick={this.repasswordFun}>找回密码</div> */}
                {/*<FormItem  label='验证码'  {...VerifLayout}>*/}
                {/*{getFieldDecorator('VerifCode', {*/}
                {/*rules: [{ required: true, message: '请输入验证码!' }]*/}
                {/*})(*/}
                {/*<Input />*/}
                {/*)}*/}
                {/*<ImgElement keyNum={this.state.keyNum} />*/}

                {/*</FormItem>*/}

                <FormItem style={{ textAlign: 'center' }}>
                  <Button type="primary" htmlType="submit" className="login-form-button" >
                    登&nbsp;&nbsp;录
                    </Button>
                </FormItem>
              </Form>
            </div>
            {/* <div className={Style.regBtn}>
                <Button type="primary" htmlType="submit" className={Style.regFormButton} onClick={this.registerFun} >
                  注&nbsp;&nbsp;册
                </Button>
              </div> */}
          </div>
        </div>


      </div>
    )
  }
}

App.contextTypes = {
  router: React.PropTypes.object
}

function mapStateToProps(state, ownProps) {
  return {
    userMsg: state.login.userMsg,
    data: state.login.data.data
  }
}
function dispatchToProps(dispatch) {
  return {
    saveUser(payload, params) {
      dispatch({
        type: 'login/saveUser',
        payload
      })
    },
    queryUser(payload, params) {
      dispatch({
        type: 'login/queryAdminUser',
        payload
      })
    }
  }
}
export default connect(mapStateToProps, dispatchToProps)(Form.create()(App));
